package com.tosit.bmx.controller.user;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.tosit.bmx.common.json.JSONModel;
import com.tosit.bmx.common.json.JSONUtil;
import com.tosit.bmx.common.shiro.BanException;
import com.tosit.bmx.common.shiro.CustomizedToken;
import com.tosit.bmx.common.shiro.ExpireException;
import com.tosit.bmx.common.util.DateUtil;
import com.tosit.bmx.common.util.Sha1Util;
import com.tosit.bmx.domian.Muser;
import com.tosit.bmx.domian.User;
import com.tosit.bmx.service.user.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;

/**
 * 用户使用的接口
 *
 * @author tsl
 * @create 2018-04-19 12:07
 **/
@Controller
@RequestMapping()
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    Producer captchaProducer;
    /**
     * 用户登录
     * @author tsl
     * @date 2018/4/20 17:47
     * @param name
     * @param pwd
     * @param model
     * @param type 1汉 2藏
     * @return
     */
    @RequestMapping(value = "/user/login")
    public String adminLogin(/*@RequestParam("name") String securityCode,*/Integer type,@RequestParam("name") String name, @RequestParam("pwd") String pwd, Model model,HttpServletRequest request) {
        String resultUrl = "/user/zlogin";
        if (type==1) {
            resultUrl = "/user/login";
        }
        Subject subject = SecurityUtils.getSubject();
        CustomizedToken usernamePasswordToken = new CustomizedToken(name, pwd, "User");
        usernamePasswordToken.setRememberMe(true);
        try {
            subject.login(usernamePasswordToken);
            if (subject.isAuthenticated()) {
                User user = userService.findsUserByName(name);
                user.setIsOnline(1);
                user.setIp(getIpAddr(request));
                user.setUpdatetime(new Date().getTime()/1000+"");
                userService.modifyUser(user);
                user.setPassword(null);
                subject.getSession().setAttribute("user", user);
                if (type==1){
                    return "redirect:/p/user/user-index";
                }else {
                    return "redirect:/p/user/zuser-index";
                }
            }
        } catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                if (type==1){
                    model.addAttribute("msg", "此用户不存在");
                }else {
                    model.addAttribute("msg", "དེའི་སྤྱོད་མཁན་མི་གནས་པ།");
                }

            }
            if (e instanceof IncorrectCredentialsException) {
                if (type==1){
                    model.addAttribute("msg", "您的密码错误");
                }else {
                    model.addAttribute("msg", "ཁྱེད་ཀྱི་གསང་བའི་ནོར་འཁྲུལ།");
                }
            }
            if (e instanceof BanException) {
                if (type==1){
                    model.addAttribute("msg", "您的账号已经被锁");
                }else {
                    model.addAttribute("msg", "ཁྱེད་ཀྱི་རྩིས་ཐོའི་ཨང་གྲངས་ཟིན་པའི་ཟྭ།");
                }
            }

            if (e instanceof ExpireException) {
                if (type==1){
                    model.addAttribute("msg", "您的账号已到期");
                }else {
                    model.addAttribute("msg", "ཁྱེད་ཀྱི་རྩིས་ཐོའི་ཨང་གྲངས་ཟིན་པ་ཐིམ་པ།");
                }
            }


        }
        return  resultUrl;
    }




    /**
     * 用户登出
     * @author tsl
     * @date 2018/4/20 17:48
     * @param type 1汉 2藏
     * @return
     */
    @RequestMapping("/user/loginOut")
    public String loginOut(Integer type) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getSession().getAttribute("user");
        if(user!=null){
            user.setIsOnline(0);
            userService.modifyUser(user);
        }
        subject.logout();


       /* SecurityManager securityManager = SecurityUtils.getSecurityManager();
        Subject.Builder builder = new Subject.Builder(securityManager);
        builder.sessionId(sessionId);
        Subject subject = builder.buildSubject();
        if (null != subject) {
            try {
                subject.logout();
            } catch (SessionException e) {

            }
        }*/


        if (type == 1) {
            return "redirect:/p/user/login";
        } else {
            return "redirect:/p/user/zlogin";
        }

    }
    /**
     * @Description: 获取客户端IP地址
     * @author tsl
     * @date 2018/4/20 17:48
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if(ip.equals("127.0.0.1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ip= inet.getHostAddress();
            }
        }
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ip != null && ip.length() > 15){
            if(ip.indexOf(",")>0){
                ip = ip.substring(0,ip.indexOf(","));
            }
        }
        return ip;
    }



    /**
     *  修改密码
     * @author tsl
     * @date 2018/4/27 15:58
     * @param newPwd 新密码
     * @param pwd 原密码
     * @return fixMsg 描述信息 status 对应状态 2 原密码错误  1 success
     */
    @RequestMapping(value = "/user/fm",method = RequestMethod.PUT)
    public void fixUserPwd(String newPwd,String pwd,HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();
        User user1 = (User) subject.getSession().getAttribute("user");
        User user=userService.findsUserByName(user1.getTel());
        if (Sha1Util.getSha1(pwd).equals(user.getPassword())) {
                user.setPassword(Sha1Util.getSha1(newPwd));
                userService.modifyUser(user);
                JSONModel.put("fixMsg", "修改成功，请重新登陆");
                JSONModel.put("status", 1);
        }else {
            JSONModel.put("fixMsg", "原密码错误");
            JSONModel.put("status", 2);
        }
        JSONUtil.printJsonModel(response);
    }

    /**
     * 生成带验证码的图片
     * @param model
     * @param request
     * @param response
     * @param timestamp
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getImage", method = RequestMethod.GET)
    public void getCaptchaImage(Model model, HttpServletRequest request, HttpServletResponse response,
                                        @RequestParam(value = "timestamp", required = false) String timestamp) throws IOException {
        if (StringUtils.isEmpty(timestamp)) {
            //System.out.println("没有时间戳\ttimestamp:" + timestamp);
            model.addAttribute("timestamp", System.currentTimeMillis());
        } else {
            //System.out.println("有时间戳\ttimestamp:" + timestamp);
            model.addAttribute("timestamp", timestamp);
        }
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }

    }


}
